const Archiver = require('archiver');
const _ = require('lodash');
const utils = require('../utils/utils');

class ZipAdapter {
  constructor() {
    this.files = Object.create(null);
    this.disposables = [];
  }

  append(data, { name, base64 = false }) {
    if (base64) {
      data = utils.decodeBase64ToBuffer(data);
    }
    this.files[name] = data;
  }

  appendDisposable(data, { name }) {
    this.append(data, { name });
    this.disposables.push(name);
  }

  clearDisposable() {
    this.disposables.forEach(filename => delete this.files[filename]);
  }

  toArchiver(zipOptions) {
    const zip = Archiver('zip', zipOptions);
    _.forIn(this.files, (file, name) => {
      zip.append(file, { name });
    });
    return zip;
  }
}

module.exports = ZipAdapter;
